//
//  AudioPlayViewController.swift
//  clreader
//
//  Created by colin on 2019/3/28.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

/// 音频播放界面
class AudioPlayViewController: CLBaseViewController {
    
    private lazy var imageViewPhoto = UIImageView()
    private lazy var labelTitle = UILabel()
    private lazy var buttonPlay = UIButton(type: .custom)
    private lazy var buttonPre = UIButton(type: .custom)
    private lazy var buttonNext = UIButton(type: .custom)
    private lazy var slider = CLSlider(frame: CGRect.zero)
    private lazy var labelCurrentTime = UILabel()
    private lazy var labelTotalTime = UILabel()
    
    private var playerStatusDispose:Disposable?
    private var playerProgressDispose:Disposable?
    private var playerAudioChangedDispose:Disposable?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hex: "f8f8f8")

        // 头部
        let topBar = CLNavigationBar().then {
            $0.title = ""
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        }
        topBar.show(inView: self.view)
        
        // 封面图片
        let ratio:CGFloat = 280.0 / 375.0
        self.view.addSubview(self.imageViewPhoto)
        self.imageViewPhoto.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(topBar.snp.bottom)
            make.height.equalTo(UIScreen.main.bounds.width * ratio)
        }
        
        // 标题
        self.labelTitle.do {
            $0.textColor = UIColor(hex: "343434")
            $0.font = UIFont.systemFont(ofSize: 17.0, weight: .light)
        }
        self.view.addSubview(self.labelTitle)
        self.labelTitle.snp.makeConstraints { (make) in
            make.top.equalTo(self.imageViewPhoto.snp.bottom).offset(30.0)
            make.centerX.equalToSuperview()
        }
        
        // 底部
        let bottomBar = UIView().then {
            $0.backgroundColor = UIColor.white
        }
        self.view.addSubview(bottomBar)
        bottomBar.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(70.0)
        }
        
        // 播放控制
        let viewPlayContainer = UIView().then {
            
            // 播放按钮
            self.buttonPlay.do {
                $0.setImage(UIImage(named: "button_play"), for: .normal)
                $0.addTarget(self, action: #selector(self.actionPlay(_:)), for: .touchUpInside)
            }
            $0.addSubview(self.buttonPlay)
            self.buttonPlay.snp.makeConstraints({ (make) in
                make.center.equalToSuperview()
                make.size.equalTo(CGSize(width: 84.0, height: 84.0))
            })
            
            self.buttonPre.do {
                $0.setImage(UIImage(named: "button_pre_enable"), for: .normal)
                $0.setImage(UIImage(named: "button_pre_disable"), for: .disabled)
                $0.addTarget(self, action: #selector(self.actionPre(_:)), for: .touchUpInside)
            }
            $0.addSubview(self.buttonPre)
            self.buttonPre.snp.makeConstraints({ (make) in
                make.centerY.equalTo(self.buttonPlay.snp.centerY)
                make.right.equalTo(self.buttonPlay.snp.left).offset(-30.0)
                make.size.equalTo(CGSize(width: 44.0, height: 44.0))
            })
            
            self.buttonNext.do {
                $0.setImage(UIImage(named: "button_next_enable"), for: .normal)
                $0.setImage(UIImage(named: "button_next_disable"), for: .disabled)
                $0.addTarget(self, action: #selector(self.actionNext(_:)), for: .touchUpInside)
            }
            $0.addSubview(self.buttonNext)
            self.buttonNext.snp.makeConstraints({ (make) in
                make.centerY.equalTo(self.buttonPlay.snp.centerY)
                make.left.equalTo(self.buttonPlay.snp.right).offset(30.0)
                make.size.equalTo(CGSize(width: 44.0, height: 44.0))
            })
            
            self.slider.do {
                $0.setSliderBackgroundImage(image: UIImage(named: "cm2_fm_playbar_btn"), state: .normal)
                $0.setSliderBackgroundImage(image: UIImage(named: "cm2_fm_playbar_btn"), state: .selected)
                $0.setSliderBackgroundImage(image: UIImage(named: "cm2_fm_playbar_btn"), state: .highlighted)
                
                $0.setSliderThumbImage(image: UIImage(named: "cm2_fm_playbar_btn_dot"), state: .normal)
                $0.setSliderThumbImage(image: UIImage(named: "cm2_fm_playbar_btn_dot"), state: .selected)
                $0.setSliderThumbImage(image: UIImage(named: "cm2_fm_playbar_btn_dot"), state: .highlighted)
                
                $0.minimumTrackTintColor = UIColor(hex: "AE1600")
                $0.maximumTrackTintColor = UIColor(hex: "EFEFEF")
                $0.bufferTrackTintColor = UIColor(hex: "EFEFEF")
                
                // slider 事件
                $0.handleTouchEnded  = { (progress_) in
                    let player = CLAudioPlayer.shared
                    if player.progress.value != progress_ {
                        // 快进快退
                        player.seek(to: player.totalTime * Double(progress_), completeHandle: { (complete) in
                            player.startOrResume()
                        })
                    }
                }
            }
            $0.addSubview(self.slider)
            self.slider.snp.makeConstraints { (make) in
                make.left.equalToSuperview()
                make.right.equalToSuperview()
                make.top.equalToSuperview()
                make.height.equalTo(20.0)
            }
            
            self.labelCurrentTime.do {
                $0.textColor = UIColor(hex: "848484")
                $0.font = UIFont.systemFont(ofSize: 11.0, weight: .light)
            }
            $0.addSubview(self.labelCurrentTime)
            self.labelCurrentTime.snp.makeConstraints({ (make) in
                make.left.equalToSuperview().offset(10.0)
                make.top.equalTo(self.slider.snp.bottom)
            })
            
            self.labelTotalTime.do {
                $0.textColor = UIColor(hex: "848484")
                $0.font = UIFont.systemFont(ofSize: 11.0, weight: .light)
            }
            $0.addSubview(self.labelTotalTime)
            self.labelTotalTime.snp.makeConstraints({ (make) in
                make.right.equalToSuperview().offset(-10.0)
                make.top.equalTo(self.slider.snp.bottom)
            })
            
        }
        self.view.addSubview(viewPlayContainer)
        viewPlayContainer.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(labelTitle.snp.bottom).offset(30.0)
            make.bottom.equalTo(bottomBar.snp.top)
        }
        
        // 播放状态观察
        self.playerStatusDispose = CLAudioPlayer.shared.status.observe { [weak self] (new, old) in
            // 播放按钮状态
            if new == .playing {
                self?.buttonPlay.setImage(UIImage(named: "button_pause"), for: .normal)
            } else {
                self?.buttonPlay.setImage(UIImage(named: "button_play"), for: .normal)
            }
            
            // 正在加载
            if new == .loading {
                self?.slider.showProgress()
            }
            
            // 音频总时间
            if new == .playing {
                self?.labelTotalTime.text = CLAudioPlayer.shared.totalTime.hms
            }
        }
        
        // 播放进度观察者
        self.playerProgressDispose = CLAudioPlayer.shared.progress.observe { [weak self] (new, old) in
            self?.slider.hideProgress()
            if let isDraging = self?.slider.isDraging, !isDraging {
                self?.slider.progress = new
                self?.labelCurrentTime.text = CLAudioPlayer.shared.currentTime.hms
            }
        }
        
        // 音频切换观察者
        self.playerAudioChangedDispose = CLAudioPlayer.shared.current.observe { [weak self] (new, old) in
            let current = CLAudioPlayer.shared.current.value
            
            // 封面
            if let cover_url = new?.cover_url,
                let imageUrl = URL(string: cover_url) {
                self?.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self?.imageViewPhoto.image = nil
            }
            
            // 标题
            self?.labelTitle.text = current?.title
            
            // 检查上一个下一个按钮
            self?.buttonPre.isEnabled = CLAudioPlayer.shared.hasPre
            self?.buttonNext.isEnabled = CLAudioPlayer.shared.hasNext
        }
        
        // 初始化状态
        let player = CLAudioPlayer.shared
        self.labelCurrentTime.text = player.currentTime.hms
        self.labelTotalTime.text = player.totalTime.hms
        if player.status.value == .playing {
            self.buttonPlay.setImage(UIImage(named: "button_pause"), for: .normal)
        } else {
            self.buttonPlay.setImage(UIImage(named: "button_play"), for: .normal)
        }
        
        // 检查上一个下一个按钮
        self.buttonPre.isEnabled = CLAudioPlayer.shared.hasPre
        self.buttonNext.isEnabled = CLAudioPlayer.shared.hasNext
        
    }

    /// 开始播放
    func play(audios:[CLAudio], index:Int = 0) {
        CLAudioPlayer.shared.play(audios: audios, index: index)
        
        print(audios)
        print(index)
    }
    
}

extension AudioPlayViewController {
    
    @objc private func actionPlay(_ sender:Any) {
        
        let player = CLAudioPlayer.shared
        let status = player.status.value
        if status == .paused || status == .ended {
            player.startOrResume()
        } else if status == .playing {
            player.pause()
        } else {
            // 其他状态，不作任何操作
        }
    }
    
    @objc private func actionPre(_ sender:Any) {
        let player = CLAudioPlayer.shared
        player.playPre()
    }
    
    @objc private func actionNext(_ sender:Any) {
        let player = CLAudioPlayer.shared
        player.playNext()
    }
    
}
